﻿using DAP.Adorners;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Forms = System.Windows.Forms;

namespace ZhwangTool
{
    /// <summary>
    /// AdornerUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class AdornerUserControl : UserControl
    {
        public AdornerUserControl()
        {
            InitializeComponent();

            radioButtonB.IsChecked = true;
      
        }

        ObservableCollection<LVData> lVDatas = new ObservableCollection<LVData>();


        //定义了一个名字为 _clp 的实例变量
        CroppingAdorner _clp;
        FrameworkElement _felCur = null;
        Brush _brOriginal;

        double rcLeft = 0;
        double rcTop = 0;
        double rcRight = 0;
        double rcBottom = 0;
      
        
        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            RefreshCropImage();
        }

        private void RemoveCropFromCur()
        {
            AdornerLayer aly = AdornerLayer.GetAdornerLayer(_felCur);
            aly.Remove(_clp);
        }

        private void AddCropToElement(FrameworkElement fel)
        {
            if (_felCur != null)
            {
                RemoveCropFromCur();
            }
            Rect rcInterior = new Rect(
                fel.ActualWidth * 0.2,
                fel.ActualHeight * 0.2,
                fel.ActualWidth * 0.6,
                fel.ActualHeight * 0.6);
            AdornerLayer aly = AdornerLayer.GetAdornerLayer(fel);

            if (aly==null)
            {
                return;
            }



            _clp = new CroppingAdorner(fel, rcInterior);

           

            _clp.ClipToBounds = true;
            
            aly.Add(_clp);

            imgCrop.Source = _clp.BpsCrop();

            _clp.CropChanged += CropChanged;
            _felCur = fel;
            if (rbRed.IsChecked != true)
            {
                SetClipColorGrey();
            }
        }

        public void RefreshCropImage()
        {

            if (_clp != null)
            {
                //MessageBox.Show("width" + imgChurch.ActualWidth.ToString() + "height" + imgChurch.ActualHeight.ToString());

                //ImageSource imageSource = imgChurch.Source;

                BitmapSource bitmapSource = imgChurch.Source as BitmapSource;

                if (bitmapSource==null)
                {
                    return;
                    //MessageBox.Show("width" + bitmapSource.PixelWidth.ToString() + "height" + bitmapSource.PixelHeight.ToString());
                }
                
                if (imgChurch == null)
                {
                    return;
                }

                double blxs = 1;
                
                if (imgChurch.ActualWidth > 0)
                {
                    blxs = bitmapSource.PixelWidth / imgChurch.ActualWidth;
                }

                Rect rc = _clp.ClippingRectangle;

                //tblkClippingRectangle.Text = string.Format(
                //    "Clipping Rectangle: ({0:N1}, {1:N3}, {2:N3}, {3:N3},{4:N3},{5:N3},{6:N3})",
                //    rc.Left,
                //    rc.Top,
                //    rc.Right,
                //    rc.Bottom,
                //    (rc.Right - rc.Left) * blxs,
                //    (rc.Bottom - rc.Top) * blxs,
                //blxs);

                tblkClippingRectangle.Text = string.Format("剪裁框宽度:< {0:N2} >\r\n剪裁框高度:< {1:N2} >",(rc.Right - rc.Left) * blxs,(rc.Bottom - rc.Top) * blxs);

                imgCrop.Source = _clp.BpsCrop();

                rcLeft = rc.Left;
                rcTop = rc.Top;
                rcRight = rc.Right;
                rcBottom = rc.Bottom;
            }
        }

        private void CropChanged(Object sender, RoutedEventArgs rea)
        {
            CroppingAdorner croppingAdorner = sender as CroppingAdorner;

            if (croppingAdorner==null)
            {
                MessageBox.Show("null");
            }
            else
            {
                //MessageBox.Show("x="+_clp.ClippingRectangle.TopLeft.X.ToString());

                //MessageBox.Show("y="+_clp.ClippingRectangle.TopLeft.Y.ToString());

                //MessageBox.Show("width=" + _clp.ClippingRectangle.Width.ToString());

                //MessageBox.Show("height=" + _clp.ClippingRectangle.Height.ToString());
                
            }




            RefreshCropImage();
        }



        private void SetClipColorRed()
        {
            if (_clp != null)
            {
                _clp.Fill = _brOriginal;
            }
        }

        private void SetClipColorGrey()
        {
            if (_clp != null)
            {
                Color clr = Colors.Black;
                clr.A = 110;
                _clp.Fill = new SolidColorBrush(clr);
            }
        }

        private void SetClipColorWhite()
        {
            if (_clp != null)
            {
                Color clr = Colors.White;
                clr.A = 0;
                _clp.Fill = new SolidColorBrush(clr);
            }
        }




        private void Red_Checked(object sender, RoutedEventArgs e)
        {
            SetClipColorRed();
        }

        private void Grey_Checked(object sender, RoutedEventArgs e)
        {
            SetClipColorGrey();
        }

        private void SelectPicture_Click(object sender, RoutedEventArgs e)
        {
            
            Forms.OpenFileDialog openFileDialog = new Forms.OpenFileDialog();

            // 设置文件类型过滤器，只允许用户选择图片文件  
            openFileDialog.Filter = "Image Files (*.jpg, *.jpeg, *.gif, *.bmp, *.png)|*.jpg;*.jpeg;*.gif;*.bmp;*.png";

            // 显示文件选择对话框，并获取用户选择的文件路径  
            if (openFileDialog.ShowDialog() == Forms.DialogResult.OK)
            {

                TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

                var tgnew = group.CloneCurrentValue();

                float angle = 0;

                if (tgnew != null)
                {
                    RotateTransform rt = tgnew.Children[2] as RotateTransform;

                    rt.Angle = 0;

                    group.Children[2] = rt;
                    
                }

                string selectedFilePath = openFileDialog.FileName;
                // 在这里使用用户选择的图片文件路径  
                //MessageBox.Show("Selected image: " + selectedFilePath);

                using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(selectedFilePath))
                {

                    imgChurch.Source = BitmapToBitmapImage(bitmap);

                    filePath.Text = selectedFilePath;
                }

                imgCrop.Visibility = Visibility.Collapsed;

                if (radioButtonA.IsChecked.HasValue && radioButtonA.IsChecked.Value)
                {
                    imgCrop.Visibility = Visibility.Visible;
                    
                    if (imgChurch != null)
                    {
                        AddCropToElement(imgChurch);

                        _brOriginal = _clp.Fill;

                        RefreshCropImage();

                    }

                }
             
                listFileManager.Visibility = Visibility.Collapsed;
               

                //ImageSource imageSource = imgChurch.Source;

                //BitmapSource bitmapSource = imageSource as BitmapSource;

                //if (bitmapSource != null)
                //{
                //    dpix.Text = bitmapSource.DpiX.ToString("0.00") + "--" + bitmapSource.DpiY.ToString("0.00");
                //    dpiy.Text = bitmapSource.PixelHeight.ToString("0.00") + "--" + bitmapSource.Height.ToString("0.00");

                //}
                
            }
        }

        /// <summary>
        /// 图片转换
        /// </summary>
        /// <param name="bitmap">bitmap格式图片</param>
        /// <returns></returns>
        private static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
        {
            BitmapImage bitmapImage = new BitmapImage();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                bitmapImage.BeginInit();
                bitmapImage.StreamSource = ms;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }
            return bitmapImage;
        }


        private void SavePicture_Click(object sender, RoutedEventArgs e)
        {
            TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            var tgnew = group.CloneCurrentValue();

            float angle = 0;

            if (tgnew != null)
            {
                RotateTransform rt = tgnew.Children[2] as RotateTransform;

                angle = (float)rt.Angle % 360;

                //MessageBox.Show(angle.ToString());
            }

            Forms.SaveFileDialog saveFileDialog = new Forms.SaveFileDialog();

            saveFileDialog.Filter = "Image Files (*.jpg, *.jpeg, *.gif, *.bmp, *.png)|*.jpg;*.jpeg;*.gif;*.bmp;*.png";

            Forms.DialogResult dialogResult = saveFileDialog.ShowDialog();

            string obImageFile = string.Empty;

            if (dialogResult == Forms.DialogResult.OK)
            {
                obImageFile = saveFileDialog.FileName;

            }

            string sourceImageFile = filePath.Text;


            if (System.IO.File.Exists(sourceImageFile))
            {
                using (System.Drawing.Image imageOb = System.Drawing.Image.FromFile(sourceImageFile))
                {
                    #region 尝试完善

                    //目标效果,即界面选取框相对于界面的坐标以及宽高，界面像素600*600

                    //MessageBox.Show(rcLeft.ToString()+"--"+rcRight.ToString()+"--"+rcTop.ToString()+"--"+rcBottom.ToString());

                    //x1 y1 相当于图片左上角点的矩形左上角点坐标
                    double x1 = RcLeft;
                    double y1 = rcTop;

                    //width1 height1 根据左上右下角点计算Adorner 的场合款
                    double width1 = rcRight - RcLeft;
                    double height1 = rcBottom - rcTop;

                    // 获取图片的宽度和高度  
                    double widthImage = imageOb.Width;

                    double heightImage = imageOb.Height;

                    //MessageBox.Show("原始图片的分辨率是" + imageOb.HorizontalResolution.ToString());

                    //Image控件被设置成Uniform时会自动将原图缩放，此时需要求出原图与控件呈现图的缩放比例offset

                    double width3 = imgChurch.ActualWidth;
                    //double imagewidth = imgChurch.Source.Width;
                    //double offset = imagewidth / width3;

                    double offset = widthImage / width3;


                    //MessageBox.Show("ActualWidth" + width3.ToString() + "显示宽度<" + imagewidth.ToString() + ">");

                    //MessageBox.Show(offset.ToString() + "<" + scaleX.ToString() + ">---<" + scaleY.ToString() + ">");

                    //scaleX = 1;
                    //scaleY = 1;

                    //old
                    //计算原图的裁剪位置以及宽高
                    //double x = ((x1 - x2) / scaleX) * offset;
                    //double y = ((y1 - y2) / scaleY) * offset;
                    //double width = (width1 / scaleX) * offset;
                    //double height = (height1 / scaleY) * offset;
                    //new

                    double x = x1 * offset;

                    double y = y1 * offset;

                    double width = width1 * offset;

                    double height = height1 * offset;


                    //MessageBox.Show("width=" + width.ToString());

                    //MessageBox.Show("height=" + height.ToString());

                    #endregion



                    if (angle % 180 == 0)
                    {
                        var returnBitmap = new System.Drawing.Bitmap((int)width, (int)height, imageOb.PixelFormat);

                        returnBitmap.SetResolution(imageOb.HorizontalResolution, imageOb.VerticalResolution);

                        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(returnBitmap);

                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                        if (angle == 0)
                        {
                            System.Drawing.Rectangle resultRectangle = new System.Drawing.Rectangle(0, 0, (int)width, (int)height);

                            System.Drawing.Rectangle sourceRectangle = new System.Drawing.Rectangle((int)(x), (int)(y), (int)(width), (int)(height));

                            g.DrawImage(imageOb, resultRectangle, sourceRectangle, System.Drawing.GraphicsUnit.Pixel);

                            returnBitmap.Save(obImageFile);

                        }

                        if (angle == 180)
                        {
                            g.TranslateTransform((float)width / 2, (float)height / 2);

                            g.RotateTransform(angle);

                            g.TranslateTransform(-(float)width / 2, -(float)height / 2);

                            System.Drawing.Rectangle resultRectangle = new System.Drawing.Rectangle(0, 0, (int)width, (int)height);

                            System.Drawing.Rectangle sourceRectangle = new System.Drawing.Rectangle((int)(x), (int)(y), (int)(width), (int)(height));

                            g.DrawImage(imageOb, resultRectangle, sourceRectangle, System.Drawing.GraphicsUnit.Pixel);

                            returnBitmap.Save(obImageFile);

                        }

                    }
                    else
                    {
                        var returnBitmap = new System.Drawing.Bitmap((int)height, (int)width, imageOb.PixelFormat);

                        returnBitmap.SetResolution(imageOb.HorizontalResolution, imageOb.VerticalResolution);

                        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(returnBitmap);

                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;


                        if (angle == 90 || angle == 270)
                        {
                            g.TranslateTransform((float)height / 2, (float)width / 2);

                            g.RotateTransform(angle);

                            g.TranslateTransform((float)-width / 2, (float)-height / 2);

                            System.Drawing.Rectangle resultRectangle = new System.Drawing.Rectangle(0, 0, (int)width, (int)height);

                            System.Drawing.Rectangle sourceRectangle = new System.Drawing.Rectangle((int)(x), (int)(y), (int)(width), (int)(height));

                            g.DrawImage(imageOb, resultRectangle, sourceRectangle, System.Drawing.GraphicsUnit.Pixel);

                            returnBitmap.Save(obImageFile);

                        }
                    }


                }
            }

            MessageBox.Show("程序运行完毕！");

        }

        private void ImgChurch_MouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {


            Image image = sender as Image;

            if (image == null)
            {
                return;
            }

            TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            var tgnew = group.CloneCurrentValue();

            double angle = 0;

            if (tgnew != null)
            {
                RotateTransform rt = tgnew.Children[2] as RotateTransform;

                angle = rt.Angle % 360;
                
            }

            Point point = e.GetPosition(image);

            //MessageBox.Show(point.X.ToString("0.00")+"---"+point.Y.ToString("0.00"));

            point = new Point(point.X - image.ActualWidth / 2, point.Y - image.ActualHeight / 2);
  
            double scale = e.Delta * 0.001;

            ZoomImage(group, point, scale);


            //ImageSource imageSource = imgChurch.Source;

            //BitmapSource bitmapSource = imageSource as BitmapSource;

            //if (bitmapSource != null)
            //{
            //    dpix.Text = bitmapSource.DpiX.ToString("0.00") + "--" + bitmapSource.DpiY.ToString("0.00");
            //    dpiy.Text = string.Empty;
            //    dpiy.Text = "PixelHeight" + bitmapSource.PixelHeight.ToString("0.00") + "\n" +
            //                "PixelWidth" + bitmapSource.PixelWidth.ToString("0.00") + "\n" +
            //                "Height" + bitmapSource.Height.ToString("0.00") + "\n" +
            //                "Width" + bitmapSource.Width.ToString("0.00") + "\n" +
            //                "ActualHeight" + imgChurch.ActualHeight.ToString("0.00") + "\n" +
            //                "ActualWidth" + imgChurch.ActualWidth.ToString("0.00");

            //}

            RefreshCropImage();


        }

        private static void ZoomImage(TransformGroup group, Point point, double scale)
        {

            Point pointToContent = group.Inverse.Transform(point);

            ScaleTransform transform = group.Children[0] as ScaleTransform;
            
            if (transform.ScaleX + scale < 0.5)
            {
                return;
            }

            transform.ScaleX += scale;
            transform.ScaleY += scale;

            TranslateTransform transform1 = group.Children[1] as TranslateTransform;

            transform1.X = -1 * ((pointToContent.X * transform.ScaleX) - point.X);

            transform1.Y = -1 * ((pointToContent.Y * transform.ScaleY) - point.Y);

        }



        private bool isMouseLeftButtonDown;
        private Point previousMousePoint;

        /// <summary>
        /// 暂时未用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgChurch_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Image image = sender as Image;

            if (image == null)
            {
                return;
            }

            if (this.isMouseLeftButtonDown && e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                this.DoImageMove(image, e.GetPosition(image));
            }
        }


        /// <summary>
        /// 暂时未用
        /// </summary>
        /// <param name="image"></param>
        /// <param name="position"></param>
        private void DoImageMove(Image image, Point position)
        {

            TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            TranslateTransform transform = group.Children[1] as TranslateTransform;

            transform.X += position.X - this.previousMousePoint.X;

            transform.Y += position.Y - this.previousMousePoint.Y;

            this.previousMousePoint = position;
        }

        private Cursor oldCursor;

        public double RcLeft { get => rcLeft; }


        /// <summary>
        /// 暂时未用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgChurch_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Image img = sender as Image;

            if (img == null) return;

            this.oldCursor = this.Cursor;

            this.Cursor = Cursors.SizeAll;

            img.CaptureMouse();
            this.isMouseLeftButtonDown = true;
            this.previousMousePoint = e.GetPosition(img);
        }

        /// <summary>
        /// 暂时未用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgChurch_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;

            if (img == null) return;

            this.Cursor = this.oldCursor;

            img.ReleaseMouseCapture();
            this.isMouseLeftButtonDown = false;
        }



        private void BorderPic_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            //Border border = sender as Border;

            //TransformGroup group = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            //Point point = e.GetPosition(border);

            //point = new Point(point.X - border.ActualWidth / 2, point.Y - border.ActualHeight / 2);


            ////point = new Point(0, 0);

            ////MessageBox.Show("wo yunxing le 11111 ");

            //double scale = e.Delta * 0.001;

            //ZoomImage(group, point, scale);

            //MessageBox.Show("wo yunxing le ");

            //RefreshCropImage();           

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
       
            RotateLeft(imgChurch);

        }

        /// <summary>
        /// 图片左转
        /// </summary>
        /// <param name="img">被操作的前台Image控件</param>
        public void RotateLeft(Image img)
        {
            TransformGroup tg = ImageComparePanel.FindResource("ImageCompareResources") as TransformGroup;

            //TransformGroup tg = img.RenderTransform as TransformGroup;

            var tgnew = tg.CloneCurrentValue();

            if (tgnew != null)
            {
                RotateTransform rt = tgnew.Children[2] as RotateTransform;
                
                img.RenderTransformOrigin = new Point(0.5, 0.5);

                rt.Angle += 90;

                tg.Children[2] = rt;

            }
            
        }

      

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            string str = System.Environment.CurrentDirectory;

            str = System.IO.Path.Combine(str, "Resources", "MtnChurch.jpg");

            if (System.IO.File.Exists(str))
            {
                filePath.Text = str;
            }
      
        }

        private void ImgChurch_Loaded(object sender, RoutedEventArgs e)
        {

            
            //ImageSource imageSource = imgChurch.Source;

            //BitmapSource bitmapSource = imageSource as BitmapSource;

            //if (bitmapSource!=null)
            //{
            //    dpix.Text = bitmapSource.DpiX.ToString("0.00")+"--"+ bitmapSource.DpiY.ToString("0.00");
            //    dpiy.Text = bitmapSource.PixelHeight.ToString("0.00") + "--" + bitmapSource.Height.ToString("0.00")+imgChurch.Height.ToString("0.00");
                
            //}
            
        }

        private void ImgChurch_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //if (imgChurch != null)
            //{
            //    AddCropToElement(imgChurch);

            //    _brOriginal = _clp.Fill;

            //    RefreshCropImage();

            //}

        }




        private void GetSizeBorder_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(borderPic.ActualWidth.ToString("0.0") + "borderPic--ActualWidth--ActualHeight" + borderPic.ActualHeight.ToString("0.0"));

            AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(imgChurch);

            Adorner[] adorners = adornerLayer.GetAdorners(imgChurch);
            if (adorners != null)
            {
                CroppingAdorner croppingAdorner = adorners[0] as CroppingAdorner;

                MessageBox.Show(croppingAdorner.ActualWidth.ToString("0.0")+ "croppingAdorner--ActualWidth--ActualHeight" + croppingAdorner.ActualHeight.ToString("0.0"));

                var rec = croppingAdorner.ClippingRectangle;

             



                //MessageBox.Show(rec.Width.ToString() +"----"+ rec.Height.ToString());

                //var renderTransform = croppingAdorner.RenderTransform;

                //MessageBox.Show(croppingAdorner.RenderSize.Width.ToString()+"--"+croppingAdorner.RenderSize.Height.ToString());

                //TransformGroup tg = croppingAdorner.RenderTransform as TransformGroup;

                //var tt = croppingAdorner.RenderTransform;

                //if (tg!=null)
                //{
                //    var trans = tg.Children[0] as ScaleTransform;

                //    MessageBox.Show(trans.ScaleX.ToString()+"--"+trans.ScaleY.ToString());

                //}
                //MessageBox.Show(croppingAdorner.AdornedElement.RenderSize.Width.ToString("0.00")+"-|-"+ croppingAdorner.AdornedElement.RenderSize.Height.ToString("0.00"));

                Image image = croppingAdorner.AdornedElement as Image;

                if (image!=null)
                {
                    TransformGroup tg = image.RenderTransform as TransformGroup;

                    if (tg != null)
                    {
                        var trans = tg.Children[0] as ScaleTransform;

                        MessageBox.Show(trans.ScaleX.ToString() + "ScaleX--ScaleY" + trans.ScaleY.ToString());

                    }
                    
                }
                
            }
            
        }


        private void ImgChurch_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                //e.Effect = DragDropEffects.All;    //重要代码：表明是所有类型的数据，比如文件路径

                e.Effects = DragDropEffects.Link;
            
            else
                e.Effects = DragDropEffects.None;

        }

        private void ImgChurch_Drop(object sender, DragEventArgs e)
        {
            string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);

            if (filePaths != null && filePaths.Length > 0)
            {
                string selectedFilePath = filePaths[0];

                string fileExtension = System.IO.Path.GetExtension(selectedFilePath).ToLower();


                string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".bmp"};

                if (imageExtensions.Contains(fileExtension))
                {
                    filePath.Text = selectedFilePath;

                    //MessageBox.Show(filePath.Text);

                    using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(filePath.Text))
                    {
                        imgChurch.Source = BitmapToBitmapImage(bitmap);
                        
                    }

                }

                
            }
            
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {

            BitmapSource imageSource = this.imgChurch.Source as BitmapSource;

            if (imageSource==null)
            {
                return;
            }

            //根据原始图像的像素数宽、高以及目标图像的像素数宽、高计算计算剪裁框的大小，
            //根据调整到近似像素数

            #region 计算给定像素数宽、高的 rcInterior

            //x1 y1 相当于图片左上角点的矩形左上角点坐标
            double x1 = RcLeft;
            double y1 = rcTop;

            //width1 height1 根据左上右下角点计算Adorner 的长和宽
            double width1 = rcRight - RcLeft;
            double height1 = rcBottom - rcTop;

            //当前接近给定像素宽度、像素高度的剪裁框的中心坐标

            double cenWidth = RcLeft + width1 / 2;
            double cenHeigh = rcTop + height1 / 2;

            // 获取图片的像素宽度和高度  
            double pixelWidthImage = imageSource.PixelWidth;
            double pixelHeightImage = imageSource.PixelHeight;

            double objPixelWidth = 0;

            double objPixelHeigh = 0;

            bool b = double.TryParse(textBoxWidth.Text, out objPixelWidth);
            bool bb = double.TryParse(textBoxHeight.Text, out objPixelHeigh);
            
            //装换失败，或者不在合理范围，退出执行。
            if (b && bb == false || objPixelWidth < 0 || objPixelHeigh < 0 || objPixelWidth > pixelWidthImage || objPixelHeigh > pixelHeightImage)
            {
                return;
            }

            double widthScale = 1;

            double heightScale = 1;

            widthScale = objPixelWidth / pixelWidthImage;
            heightScale = objPixelHeigh / pixelHeightImage;


            //MessageBox.Show("原始图片的像素宽度和像素宽度是{0}，像素高度是{1}" +pixelWidthImage.ToString()+"--"+pixelHeightImage.ToString());

            //MessageBox.Show(imgChurch.ActualWidth.ToString()+""+imgChurch.ActualHeight.ToString());

            //MessageBox.Show("-Width-" + imgChurch.Width.ToString()+ "-Height-" + imgChurch.Height.ToString());

            //根据指定大小的像素宽度高度，计算剪裁框的大小，--通过内插计算所需的剪裁框大小

            //根据给定的剪裁框大小，剪裁框的中心坐标，计算剪裁框的左上角坐标
            Rect rcInterior = new Rect(
                                        cenWidth-this.imgChurch.ActualWidth * widthScale/2,
                                        cenHeigh- this.imgChurch.ActualHeight * heightScale/2,
                                        this.imgChurch.ActualWidth * widthScale,
                                        this.imgChurch.ActualHeight * heightScale);
            
            #endregion
            
            if (_clp!=null)
            {
                RemoveCropFromCur();
            }
            
            AdornerLayer aly = AdornerLayer.GetAdornerLayer(this.imgChurch);
            _clp = new CroppingAdorner(this.imgChurch, rcInterior);

            _clp.ClipToBounds = true;

            aly.Add(_clp);

            imgCrop.Source = _clp.BpsCrop();

            _clp.CropChanged += CropChanged;
            _felCur = this.imgChurch;
            if (rbRed.IsChecked != true)
            {
                SetClipColorGrey();
            }

            RefreshCropImage();



        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            SetClipColorWhite();
        }



        private void ListFileManager_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBox = sender as ListBox;

            var selectedItem = listBox.SelectedItem as LVData;

            if (selectedItem != null)
            {

                BitmapImage myBitmapImage = new BitmapImage(new Uri(selectedItem.FullName));
                
                imgChurch.Source = myBitmapImage;

                myBitmapImage = null;

                filePath.Text = selectedItem.FullName;

            }
        }

        private void ListFileManager_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void SelectPath_Click(object sender, RoutedEventArgs e)
        {
            lVDatas.Clear();

            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();

            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //textBox1.Text = folderBrowserDialog.SelectedPath;

                listFileManager.Visibility = Visibility.Visible;
            }

            double objWidth = 150;

            
            try
            {
                ImageTexture2DView(folderBrowserDialog.SelectedPath, objWidth);

                if (radioButtonA.IsChecked.HasValue && radioButtonA.IsChecked.Value)
                {
                    imgCrop.Visibility = Visibility.Visible;
                }
                else
                {
                    imgCrop.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception)
            {
                imgChurch.Source = null;
            }
        }

        private void ImageTexture2DView(string path, double objWidth)
        {
            var apps = System.IO.Directory.GetFiles(path);

            foreach (var app in apps)
            {
                var fi = new System.IO.FileInfo(app);

                if (fi.Extension.ToLower() == ".jpg")
                {
                    string tmpName = fi.Name.Remove(fi.Name.LastIndexOf("."));

                    // Create source
                    BitmapImage bitmapImage = new BitmapImage();

                    // BitmapImage.UriSource must be in a BeginInit/EndInit block

                    bitmapImage.BeginInit();

                    bitmapImage.UriSource = new Uri(fi.FullName);


                    // To save significant application memory, set the DecodePixelWidth or
                    // DecodePixelHeight of the BitmapImage value of the image source to the desired
                    // height or width of the rendered image. If you don't do this, the application will
                    // cache the image as though it were rendered as its normal size rather than just
                    // the size that is displayed.
                    // Note: In order to preserve aspect ratio, set DecodePixelWidth
                    // or DecodePixelHeight but not both.

                    bitmapImage.DecodePixelWidth = (int)objWidth;

                    bitmapImage.EndInit();
                    //set image source

                    LVData lVData = new LVData { Name = tmpName, Pic = bitmapImage, FullName = fi.FullName };

                    lVDatas.Add(lVData);

                }

            }
            listFileManager.ItemsSource = lVDatas;
        }

        private void RadioButtonA_Checked(object sender, RoutedEventArgs e)
        {
            if (imgChurch != null)
            {
                AddCropToElement(imgChurch);

                //_brOriginal = _clp.Fill;

              

              

            }
            if (_clp!=null)
            {
                _brOriginal = _clp.Fill;
            }

            RefreshCropImage();

            if (imgCrop!=null)
            {
                imgCrop.Visibility = Visibility.Visible;

                imgCrop.Opacity = 0;

            }





        }
        
        private void RadioButtonB_Checked(object sender, RoutedEventArgs e)
        {
            if (_clp != null)
            {
                RemoveCropFromCur();
            }
            if (imgCrop!=null)
            {
                imgCrop.Visibility = Visibility.Collapsed;
            }

          


            //if (cutBoundsGrid!=null)
            //{
            //    cutBoundsGrid.Visibility = Visibility.Collapsed;
            //}
            //if (cutBoundsGrid!=null)
            //{
            //    cutBoundsGrid.Visibility = Visibility.Collapsed;
            //}


            //if (listFileManager!=null)
            //{
            //    listFileManager.Visibility = Visibility.Collapsed;
            //}



        }
    }
    
}
